<template>
  <!-- 电价快搜 -->
  <a-modal
    v-model:open="visible"
    title="电价快搜"
    @ok="handleOk"
    class="addStation"
    destroyOnClose
    :width="1000"
    @cancel="cancel"
    centered
  >
    <div class="content">
      <a-form :model="filterForm" layout="inline">
        <a-form-item label="省份">
          <a-select
            ref="select"
            v-model:value="filterForm.provId"
            class="formInput"
            placeholder="省份"
            show-search
            optionFilterProp="label"
            @change="changeProv"
          >
            <a-select-option
              v-for="item in provList"
              :key="item.provId"
              :value="item.provId"
              :label="item.provName"
            >
              {{ item.provName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="日期">
          <a-date-picker
            v-model:value="filterForm.date"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            :allowClear="false"
          />
        </a-form-item>
        <a-button
          type="primary"
          class="filterBtn"
          @click="getEleChart"
          :loading="loading"
          >查询</a-button
        >
      </a-form>
      <div
        id="eleChart"
        style="width: 100%; height: 400px"
        v-if="chartList.length"
        key="eleChart"
      ></div>
      <a-empty
        v-if="!chartList.length"
        style="opacity: 0.5; margin-top: 50px"
      />
    </div>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">关闭</a-button>
      </div>
    </template>
  </a-modal>
</template>
<script setup>

import * as echarts from "echarts";
import {
  chartOption,
  chartHalfHourOption,
  jianQi,
  fengQi,
  pingQi,
  guQi,
  shenGuQi,
} from "./chartOption";
import { HOUR_XAXIS, HALF_XAXIS_LIST } from "@/constants/dispatchCenter";

import { cloneDeep } from "lodash-es";
const $api = inject("$api");
const props = defineProps({
  eleChartVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
  provList: {
    type: Array,
  },
});
const loading = ref(false);
const visible = ref(props.eleChartVisible);
const emits = defineEmits(["update:eleChartVisible"]);
watch(
  () => props.eleChartVisible,
  (val) => {
    visible.value = val;
  }
);
const labelCol = { style: { width: "140px" } };
const formRef = ref(null);
const filterForm = ref({
  provId: 440000,
  date: null,
});

const cancel = () => {
  emits("update:eleChartVisible", false);
};
const timeRangeMappings = {
  superPeakTimeRange: "superPeakPrice",
  peakTimeRange: "peakPrice",
  flatTimeRange: "flatPrice",
  valleyTimeRange: "valleyPrice",
  deepValleyTimeRange: "deepValleyPrice",
};
const timeRangeChart = {
  superPeakTimeRange: jianQi,
  peakTimeRange: fengQi,
  flatTimeRange: pingQi,
  valleyTimeRange: guQi,
  deepValleyTimeRange: shenGuQi,
};

const getSortedTimeRanges = (data) => {
  const result = [];
  data.forEach((item) => {
    for (const [key, value] of Object.entries(item)) {
      // 如果当前字段是一个时间区间字符串（且数组非空）
      if (key.endsWith("TimeRange") && value) {
        // 分割出时间范围，并提取时间点
        const timeRanges = value.split(",").flatMap((range) => {
          const [start, end] = range.split("-");
          const startMinutes = parseInt(start.split(":")[0]);
          const endMinutes = parseInt(end.split(":")[0]);
          // 生成时间点的数组
          return Array.from({ length: endMinutes - startMinutes }, (_, i) => {
            const hour = startMinutes + i;
            return hour.toString().padStart(2, "0") + ":00";
          });
        });
        // 生成结果对象
        result.push({
          key: key,
          time: [...new Set(timeRanges)].sort(),
          value: item[timeRangeMappings[key]],
        });
      }
    }
  });
  return result;
};
const getHalfHourTimeRanges = (data) => {
  const result = [];
  data.forEach((item) => {
    for (const [key, value] of Object.entries(item)) {
      // 如果当前字段是一个时间区间字符串（且数组非空）
      if (key.endsWith("TimeRange") && value) {
        // 分割出时间范围，并提取时间点
        const timeRanges = value.split(",").flatMap((range) => {
          const [start, end] = range.split("-");
          // 解析开始时间和结束时间
          const [startHour, startMinute] = start.split(":").map(Number);
          const [endHour, endMinute] = end.split(":").map(Number);
          const timePoints = [];
          let currentHour = startHour;
          let currentMinute = startMinute;
          // 生成时间点的数组
          while (currentHour < endHour || (currentHour === endHour && currentMinute < endMinute)) {
            const formattedTime = `${currentHour.toString().padStart(2, "0")}:${currentMinute.toString().padStart(2, "0")}`;
            timePoints.push(formattedTime);
            // 增加30分钟
            currentMinute += 30;
            if (currentMinute >= 60) {
              currentMinute = 0;
              currentHour += 1;
            }
          }
          return timePoints;
        });
        // 生成结果对象
        result.push({
          key: key,
          time: [...new Set(timeRanges)].sort(),
          value: item[timeRangeMappings[key]],
        });
      }
    }
  });
  return result;
};
const initHalfChart = async () => {
  await nextTick();
  const chartEl = document.getElementById("eleChart");
  if (!chartEl) {
    return;
  }
  const chart = echarts.init(chartEl);
  const option = cloneDeep(chartHalfHourOption);
  option.series = [];

  // 获取排序后的时间范围数组，然后将其根据时间进行排序，取时间段的第一个值进行比对即可
  let sortedTimeRanges = getHalfHourTimeRanges(chartList.value);
  sortedTimeRanges = sortedTimeRanges.sort(
    (a, b) => a.time[0].split(":")[0] - b.time[0].split(":")[0]
  );
  if (sortedTimeRanges.length) {
    for (const item of sortedTimeRanges) {
      const chartData = timeRangeChart[item.key];
      chartData.data = HALF_XAXIS_LIST.map((hour) => {
        if (item.time.includes(hour)) {
          return item.value;
        } else {
          return "-";
        }
      });
      option.series.push(chartData);
    }
  }
  chart.setOption(option, true);
};
const initChart = async () => {
  await nextTick();
  const chartEl = document.getElementById("eleChart");
  if (!chartEl) {
    return;
  }
  const chart = echarts.init(chartEl);
  const option = cloneDeep(chartOption);
  option.series = [];
  // 获取排序后的时间范围数组，然后将其根据时间进行排序，取时间段的第一个值进行比对即可
  let sortedTimeRanges = getSortedTimeRanges(chartList.value);
  sortedTimeRanges = sortedTimeRanges.sort(
    (a, b) => a.time[0].split(":")[0] - b.time[0].split(":")[0]
  );
  if (sortedTimeRanges.length) {
    for (const item of sortedTimeRanges) {
      const chartData = timeRangeChart[item.key];
      chartData.data = HOUR_XAXIS.map((hour) => {
        if (item.time.includes(hour)) {
          return item.value;
        } else {
          return "-";
        }
      });
      option.series.push(chartData);
    }
  }
  chart.setOption(option, true);
};
const chartList = ref([]);
const getEleChart = async () => {
  if (!filterForm.value.date) {
    message.error("请选择日期");
    return;
  }
  const params = {
    provId: filterForm.value.provId,
    date: filterForm.value.date,
  };
  loading.value = true;
  const res = await $api.elecRuleFastQuery(params);
  loading.value = false;
  if (res && res.code === 0) {
    chartList.value = res.data;
    if(res.data.length && res.data[0]?.timeQuantum === 0){
      initHalfChart();
    } else {
      initChart();
    }
    
  }
};
onMounted(() => {});
</script>

<style lang="less" scoped>
.form {
  padding: 0 40px;
  margin-top: 30px;
}
.filterBtn {
  margin: 0 20px 20px 0;
  &:last-child {
    margin-right: 0;
  }
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
.formInput {
  width: 150px;
}
.content {
  margin-top: 20px;
  // padding: 0 10px;
}
@jian: #ec7f8c;
@feng: #f59a23;
@ping: #ffff80;
@gu: #96f203;
@shenGu: #81d3f8;
</style>